package cn.dceast.former.controller;

import cn.dceast.common.data.RtnData;
import cn.dceast.common.utils.ComConstants;
import cn.dceast.common.utils.ExcelDataUtil;
import cn.dceast.common.utils.StringUtil;
import cn.dceast.former.model.EyeModelUploadCloum;
import cn.dceast.former.service.EyeUploadInfoService;
import cn.dceast.former.service.FileDataService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fanbo on 2017-05-22.
 */
@Controller
@RequestMapping("/fileUploadController")
@Api(tags = {"fileUploadController"})
public class FileUploadController {
    public static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private FileDataService fileDataService;


    @Autowired
    private EyeUploadInfoService eyeUploadInfoService;

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    @ResponseBody
    public  String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }


    @ApiOperation(value = "上传源文件表对应关系信息保存",notes = "上传源文件表信息保存")
    @RequestMapping(value="/saveTableInfo.do", method=RequestMethod.POST)
    @ResponseBody
    public RtnData saveTableInfo(@RequestParam(required = true) String eye_model_id,
                                 @RequestParam(required = true) String Relate){

        if(StringUtil.isEmpty(eye_model_id)){
            return RtnData.fail("","模型ID为空");
        }
        if(StringUtil.isEmpty(Relate)){
            return RtnData.fail("","请上传数据");
        }

        try {
        /*
          保存之前先将之前的数据进行删除。
         */
            eyeUploadInfoService.deleteDataByModelId(Integer.parseInt(eye_model_id));
            //重新存入新值
            JSONArray jsList = JSONObject.parseArray(Relate);
            for (Object obj : jsList) {
                JSONObject jsObj = (JSONObject) obj;
                String tableName = jsObj.getString("tableName");
                String tableNameVal = jsObj.getString("tableNameVal");
                String dataCname = jsObj.getString("dataCname");
                String dataVname = jsObj.getString("dataVname");
                String newDataCname = dataCname.substring(0, dataCname.length() - 1);
                String newDataVname = dataVname.substring(0, dataVname.length() - 1);
                Object[] cnameObj = newDataCname.split(";");
                Object[] vnameObj = newDataVname.split(";");
                int index = 0;
                for (Object cname : cnameObj) {
                    EyeModelUploadCloum emuc = new EyeModelUploadCloum();
                    emuc.setTablename(tableName);
                    emuc.setCloum1(tableNameVal);
                    emuc.setCloumname(cname != null ? cname.toString() : "");
                    emuc.setModelid(Integer.parseInt(eye_model_id));
                    if(index==vnameObj.length){
                        continue;
                    }
                    emuc.setValname(vnameObj[index] != null ? vnameObj[index].toString() : "");
                    emuc.setOnlyvalue("--");
                    emuc.setSkewvalue("--");
                    emuc.setStandvalue("--");
                    //判断该字段所有的值是否是数值型
                    Map<String,Object> paramMap = new HashMap<>();
                    paramMap.put("tableName",tableName);
                    paramMap.put("dataCname",cname);
                    List<Map<String,Object>> dataNumList = eyeUploadInfoService.checkDataIsNum(paramMap);
                    if(dataNumList!=null && dataNumList.size()>0){
                        Map<String,Object> rtnMap = dataNumList.get(0);
                        Integer numCount = rtnMap.get("nums")!=null?Integer.parseInt(rtnMap.get("nums").toString()):0;
                        if(numCount>0){
                            emuc.setMaxvalueEd("--");
                            emuc.setMinvalueEd("--");
                            emuc.setAveragevalue("--");
                        }else {
                            emuc.setMaxvalueEd(rtnMap.get("maxVal") != null ? rtnMap.get("maxVal").toString() : "--");
                            emuc.setMinvalueEd(rtnMap.get("minVal") != null ? rtnMap.get("minVal").toString() : "--");
                            emuc.setAveragevalue(rtnMap.get("averVal") != null ? rtnMap.get("averVal").toString() : "--");
                        }
                        emuc.setValidvalue(rtnMap.get("validValue")!=null?rtnMap.get("validValue").toString():"--");
                    }else{
                        emuc.setMaxvalueEd("--");
                        emuc.setMinvalueEd("--");
                        emuc.setAveragevalue("--");
                        emuc.setValidvalue("--");
                    }

                    index = index + 1;
                    eyeUploadInfoService.saveUploadInfo(emuc);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return RtnData.fail("","系统出错！请联系开发人员");
        }
        return RtnData.ok("","数据保存成功");
    }

    @ApiOperation(value = "编辑页面进入上传文件的页面",notes = "编辑页面进入上传文件的页面")
    @RequestMapping(value="/getUploadTableData.do", method=RequestMethod.GET)
    @ResponseBody
    public RtnData getUploadTableData(@RequestParam(required = true) String modelId){
        List<Map<String,Object>> list = eyeUploadInfoService.getUploadTableData(modelId);
        if(list!=null && list.size()>0) {

            Map<String, Object> rtnMap = new HashMap<>();
            rtnMap.put("list", list);
            List<Object[]> listNameObj = new ArrayList<>();
            List<Object[]> listCloumObj = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (Map<String, Object> map : list) {

                    String tableName = map.get("tableName") != null ? map.get("tableName").toString() : "";
                    String cloum1 = map.get("cloum1") != null ? map.get("cloum1").toString() : "";
                    String valNames = map.get("valNames") != null ? map.get("valNames").toString() : "";
                    String cloumNames = map.get("tableName") != null ? map.get("cloumNames").toString() : "";
                    Object[] valNameObjs = valNames.split(";");
                    Object[] cloumObjs = cloumNames.split(";");
                    listNameObj.add(valNameObjs);
                    listCloumObj.add(cloumObjs);
                }
            }
            rtnMap.put("listName", listNameObj);
            rtnMap.put("listCloum", listCloumObj);

            return RtnData.ok(rtnMap);
        }else {
            return RtnData.fail("","没有数据");
        }

    }


    /**
     *
     * @param multipartFile
     * @return
     */
    @ApiOperation(value = "单文件上传",notes = "单文件上传")
    @RequestMapping(value="/upload.do", method=RequestMethod.POST)
    @ResponseBody
    public RtnData handleFileUpload(
                                    // @RequestParam(required = true) String dataType,
                                    @RequestParam("file") MultipartFile multipartFile){

        List<Map<String,List>> excelList = getExcelData(multipartFile);
        String resultData = fileDataService.saveExcelData(excelList != null && excelList.size()>0 ? excelList.get(0).get("data") : null);
        if(StringUtil.isNotEmpty(resultData)){
            List<Map<String,Object>> titleList = excelList!=null?excelList.get(0).get("title"):null;
            if(titleList!=null && titleList.size()>0){
                String tableName = multipartFile.getOriginalFilename(); // 原始文件名
                Map<String,Object> tableMap = new HashMap<>();
                tableMap.put("tableName",tableName);
                tableMap.put("className",resultData);
                titleList.add(tableMap);
                return  RtnData.ok(titleList);
            }else {
                return RtnData.fail("上传失败");
            }
        }else{
            return RtnData.fail("上传失败");
        }
    }

    @ApiOperation(value = "删除上传的表数据", notes = "删除上传的表数据")
    @RequestMapping(value="/upload/deleteTableByName.do", method=RequestMethod.POST)
    @ResponseBody
    public RtnData deleteTableByName(@RequestParam(required = true) String className){
        Integer deleteReturn = fileDataService.deleteTableByName(className);
        if(deleteReturn>0){
            fileDataService.deleteContactInfoByTableName(className);
            return RtnData.ok("删除成功");
        }else{
            return RtnData.fail("删除失败");
        }

    }


    @ApiOperation(value = "多文件上传", notes = "多文件上传")
    @RequestMapping(value="/upload/muchFile.do", method=RequestMethod.POST)
    @ResponseBody
    public RtnData batchUpload(@RequestParam(required = true) String modelId,
                               @RequestParam(required = true) String userId,
//                               @RequestParam("file1") MultipartFile file1,
//                               @RequestParam("file2") MultipartFile file2,
                               @RequestParam("files") MultipartFile[] files  ) {
//        MultipartFile[] files = new  MultipartFile[2];
//        files[0] = file1;
//        files[1] = file2;
        if (files != null && files.length > 0) {
            List<List<Map<String, Object>>> returnList = new ArrayList<>();
            for (MultipartFile multipartFile : files) {
                List<Map<String, List>> excelList= getExcelData(multipartFile);

                List<Map<String,Object>> titleList = excelList!=null?excelList.get(0).get("title"):null;
                returnList.add(titleList);
            }
            return  RtnData.ok(returnList);
        } else {
            return RtnData.fail("文件为空，上传失败！");
        }
    }


    /**
     * 获取导入表数据
     * @param multipartFile
     * @return
     */
    public List<Map<String, List>> getExcelData(MultipartFile multipartFile) {
        List<Map<String,List>> excelList = new ArrayList<>();
        if (!multipartFile.isEmpty()) {
            String sourceName = multipartFile.getOriginalFilename(); // 原始文件名
            String fileType = sourceName.substring(sourceName.lastIndexOf("."));//文件格式.xls
            String filePath = ComConstants.UPLOAD_FILE_URL;
            if (fileType.equals(".xls") || fileType.equals(".xlsx") || fileType.equals(".csv")) {
                //随即数重命名文件
                String dataType = sourceName.substring(0, sourceName.lastIndexOf("."));
                String fileName = String.valueOf(System.currentTimeMillis()) + fileType;
                File dir = new File(filePath);
                if (!dir.exists()) {
                    System.out.println(dir.mkdirs());
                }

                String newPath = filePath + fileName;
            try {
                //上传文件，临时存储upload/file/
                multipartFile.transferTo(new File(newPath));
                excelList = ExcelDataUtil.readExcelContent(newPath,multipartFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //无论如何，尝试去删除导入的文件，避免占用过多资源
                ExcelDataUtil.deleteFile(newPath);
            }
        }
        }
        return excelList;
    }
    @ApiOperation(value = "数据清单导出", notes = "数据清单导出")
    @RequestMapping(value="/down/exportExcel.do", method=RequestMethod.GET)
    @ResponseBody
    public RtnData exportExcel(HttpServletResponse response, @RequestParam(required = true) int userId,
                               @RequestParam(required = true) int modelId,
                               @RequestParam(required = true) String modelResultName,
                               @RequestParam(required = true) String fileName) {
        try {
            String fileName1 = new String(fileName.getBytes("gb2312"), "iso8859-1") + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName1);
            response.setCharacterEncoding("utf-8");
        }catch (Exception e) {
            e.printStackTrace();
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> returnList = new ArrayList<>();

        // 创建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        XSSFSheet sheet = workbook.createSheet("sheet");
        ExportInternalUtil exportUtil = new ExportInternalUtil(workbook,sheet);
        XSSFCellStyle headOneStyle = exportUtil.getHeadByOneStyle();
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        XSSFCellStyle headByTowStyle = exportUtil.getHeadByTowStyle();
        // 添加表头行
        XSSFRow hssfRow = sheet.createRow(0);
//        CellRangeAddress cra_1=new CellRangeAddress(0, 0, 0, 9);
//        sheet.addMergedRegion(cra_1);
//        row.setHeight((short)1000);
        // 设置单元格格式居中
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        if(returnList!=null && returnList.size()>0){
            Object[] titleObj= (Object[]) returnList.get(0).get("title");
            // 添加表头内容
            for(int i = 0;i<titleObj.length;i++) {
                if(titleObj[i]==null) continue;
                XSSFCell headCell = hssfRow.createCell(i);
                headCell.setCellStyle(headOneStyle);
                headCell.setCellValue(titleObj[i].toString());
                headCell.setCellStyle(cellStyle);
            }
            Object[] headObj = (Object[]) returnList.get(0).get("header");
            // 添加数据内容
            for (int n = 1; n < returnList.size(); n++) {
                hssfRow = sheet.createRow(n);
                // 创建单元格，并设置值
                for (int j = 0; j < headObj.length; j++) {
                    if(headObj[j]==null) continue;
                    XSSFCell cell = hssfRow.createCell(j);
                    cell.setCellStyle(bodyStyle);
                    String dataValue = returnList.get(n).get(headObj[j].toString())!=null?returnList.get(n).get(headObj[j].toString()).toString():"";
                    cell.setCellValue(dataValue);
                    cell.setCellStyle(cellStyle);
                }

            }
        }else{
            return RtnData.fail("暂时数据导出");
        }

        // 保存Excel文件
        try {
            workbook.write(outputStream);
            if(outputStream!=null) {
                outputStream.flush();
                outputStream.close();
            }
            return RtnData.ok("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RtnData.fail("导出失败");
        }
    }

    private static class ExportInternalUtil {

        private XSSFWorkbook wb = null;
        private XSSFSheet sheet = null;

        /**
         * @param wb
         * @param sheet
         */
        public ExportInternalUtil(XSSFWorkbook wb, XSSFSheet sheet) {
            this.wb = wb;
            this.sheet = sheet;
        }

        /**
         * 设置第一行样式
         * @return
         */
        public XSSFCellStyle getHeadByOneStyle() {
            // 创建单元格样式
            XSSFCellStyle cellStyle = wb.createCellStyle();
            // 设置单元格的背景颜色为淡蓝色
//            cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
//            cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
            // 设置单元格居中对齐
            cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            // 设置单元格垂直居中对齐
            cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            // 创建单元格内容显示不下时自动换行
            cellStyle.setWrapText(true);
            // 设置单元格字体样式
            XSSFFont font = wb.createFont();
            // 设置字体加粗
            font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 16);
            cellStyle.setFont(font);
            // 设置单元格边框为无框
            cellStyle.setBorderLeft(XSSFCellStyle.BORDER_NONE);
            cellStyle.setBorderBottom(XSSFCellStyle.BORDER_NONE);
            cellStyle.setBorderRight(XSSFCellStyle.BORDER_NONE);
            cellStyle.setBorderTop(XSSFCellStyle.BORDER_NONE);
            return cellStyle;
        }

        /**
         * 设置第一行样式
         * @return
         */
        public XSSFCellStyle getHeadByTowStyle(){
            // 创建单元格样式
            XSSFCellStyle cellStyle = wb.createCellStyle();
            // 设置单元格的背景颜色为淡蓝色
            cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            // 设置单元格垂直居中对齐
            cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            // 创建单元格内容显示不下时自动换行
            cellStyle.setWrapText(true);
            // 设置单元格字体样式
            XSSFFont font = wb.createFont();
            // 设置字体加粗
//            font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 10);
            cellStyle.setFont(font);
            // 设置单元格边框为无框
            cellStyle.setBorderLeft(XSSFCellStyle.BORDER_NONE);
            cellStyle.setBorderBottom(XSSFCellStyle.BORDER_NONE);
            cellStyle.setBorderRight(XSSFCellStyle.BORDER_NONE);
            cellStyle.setBorderTop(XSSFCellStyle.BORDER_NONE);
            return cellStyle;
        }

        /**
         * 设置表体的单元格样式
         *
         * @return
         */
        public XSSFCellStyle getBodyStyle() {
            // 创建单元格样式
            XSSFCellStyle cellStyle = wb.createCellStyle();
            // 设置单元格居中对齐
            cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            // 设置单元格垂直居中对齐
            cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            // 创建单元格内容显示不下时自动换行
            cellStyle.setWrapText(true);
            // 设置单元格字体样式
            XSSFFont font = wb.createFont();
            // 设置字体加粗
//            font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 10);
            cellStyle.setFont(font);
            // 设置单元格边框为细线条
            cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
            //set date format
            //XSSFDataFormat format = wb.createDataFormat();
            //cellStyle.setDataFormat(format.getFormat("yyyy-MM-dd"));
            return cellStyle;
        }
    }


    /**
     * 模型缩略图上传
     * @param multipartFile
     * @param request
     * @return
     */
    @ApiOperation(value = "模型缩略图上传",notes = "模型缩略图上传")
    @RequestMapping(value="/uploadPicFile.do", method=RequestMethod.POST)
    @ResponseBody
    public RtnData uploadPicFile(@RequestParam("file") MultipartFile multipartFile,
                                HttpServletRequest request){
        if (!multipartFile.isEmpty()) {

            String sourceName = multipartFile.getOriginalFilename(); // 原始文件名
            String fileType = sourceName.substring(sourceName.lastIndexOf("."));//文件格式.xls
            String filePath = ComConstants.UPLOAD_FILE_URL;
            if (fileType.equals(".jpg") || fileType.equals(".jpeg") ||
                        fileType.equals(".gif") || fileType.equals(".png")) {
                //随即数重命名文件
                String fileName = String.valueOf(System.currentTimeMillis()) + fileType;
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                String newPath = filePath + fileName;
                try {
                    //上传文件/
                    multipartFile.transferTo(new File(newPath));

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("上传图片失败");
                    RtnData.fail("error","上传图片格式错误");
                }
                RtnData.ok(newPath);
            }else{
                RtnData.fail("error","上传图片格式错误");
            }
        }
        return RtnData.fail("error","上传失败");
    }
}
